昨天我們使用自己寫的單字庫及例句,今天我們來接上Dictionary API
function getWordFromAPI(word) {
  var url = "https://api.dictionaryapi.dev/api/v2/entries/en/" + word;
  var response = UrlFetchApp.fetch(url);
  var data = JSON.parse(response.getContentText());
  // 取第一個定義與例句
  var definition = data[0].meanings[0].definitions[0].definition;
  var example = data[0].meanings[0].definitions[0].example || "例句暫無";
  return {word: word, sentence: example};
}
把單字加到 Dictionary API 的網址中。
使用 Google Apps Script 的 UrlFetchApp.fetch() 向 API 發送 GET 請求。
取得 Dictionary API 回傳的 JSON 資料。
response.getContentText() 會取得 API 回傳的文字內容(JSON 字串)。
JSON.parse() 把 JSON 字串轉成 JavaScript 物件或陣列,方便存取資料。
data[0]:取得回傳資料的第一個單字物件(API 回傳可能有多個意思)。
meanings[0]:取第一個詞性(例如名詞、動詞)。
definitions[0]:取該詞性的第一個定義。
definition:存放定義文字。
example:存放例句,如果例句不存在,用 "例句暫無" 代替。這樣就保證即使 API 沒提供例句,也不會出現錯誤。
函式最後回傳一個物件,裡面有:
word:單字本身
sentence:例句(若無例句則為 "例句暫無")
function dailyEnglishFromAPI() {
  var words = [
    "serendipity", "benevolent", "ephemeral", "meticulous",
    "cognizant", "elated", "fortuitous", "gregarious",
    "ineffable", "juxtapose"
  ];//單字清單
  // 隨機挑一個單字
  var todayWord = words[Math.floor(Math.random() * words.length)];
  // 從 Dictionary API 抓定義與例句
  var wordData = getWordFromAPI(todayWord);
  if (!wordData) return; // API 失敗或無資料
  // 組合訊息
  var message = "📚 今日單字:" + wordData.word +
                "\n\n📝 例句:" + wordData.sentence;
  // 發送到 LINE
  pushToLine(message);
}
接下來執行dailyEnglishFromAPI